package pdfsetter.core.schema;

import java.util.ArrayList;
import java.util.List;

/**
 * This class represents DocumentSchemaPattern which is composition of set of DocumetSchemaPatterns. We simply join the patterns so the result of this pattern
 * is equivalent to joining results of each pattern apart.
 * 
 * @author Andrzej Dorobisz
 */
public class CompoundDocumentSchemaPattern implements DocumentSchemaPattern {
    private final List<DocumentSchemaPattern> documentPatterns;
    private final int expectedNumberOfFiles;

    public CompoundDocumentSchemaPattern(List<DocumentSchemaPattern> documentPatterns) {
        this.documentPatterns = new ArrayList<DocumentSchemaPattern>(documentPatterns.size());
        int maxPosExpectedFileNumber = 0;
        int minNegExpectedFileNumber = 0;
        for (DocumentSchemaPattern dsp : documentPatterns) {
            this.documentPatterns.add(dsp);
            int curExpected = dsp.getExpectedNumberOfFiles();
            minNegExpectedFileNumber = Math.min(minNegExpectedFileNumber, curExpected);
            maxPosExpectedFileNumber = Math.max(maxPosExpectedFileNumber, curExpected);
        }
        if (minNegExpectedFileNumber < 0)
            expectedNumberOfFiles = -Math.max(maxPosExpectedFileNumber, -minNegExpectedFileNumber);
        else
            expectedNumberOfFiles = maxPosExpectedFileNumber;
    }

    @Override
    public DocumentSchema produceDocumentSchema(int[] fileSizes) {
        List<DocumentSchema> documentSchemas = new ArrayList<DocumentSchema>(documentPatterns.size());
        for (DocumentSchemaPattern dsp : documentPatterns) {
            documentSchemas.add(dsp.produceDocumentSchema(fileSizes));
        }
        return new CompoundDocumentSchema(documentSchemas);
    }

    @Override
    public int getExpectedNumberOfFiles() {
        return expectedNumberOfFiles;
    }

}
